<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        style="width: 200px;"
        class="filter-item"
        placeholder="请输入服务器名称"
        v-model="queryForm.name"
      >
      </el-input>
      <!-- <el-select clearable style="width: 150px" class="filter-item" v-model="queryForm.type" placeholder="请选择应用类型">
        <el-option v-for="(val, key) in Dicts.APPLICATION_TYPE" :key="key" :label="val" :value="key">
        </el-option>
      </el-select> -->
      <el-button
        class="filter-item"
        @click="doQuery"
        type="primary"
        icon="el-icon-search"
        >查询</el-button
      >
      <el-button
        v-permission="'software:add'"
        class="filter-item"
        @click="openAddDialog"
        type="success"
        icon="el-icon-plus"
        >新增</el-button
      >
    </div>
    <el-table v-loading="loading" :data="records" style="width: 100%">
      <el-table-column prop="name" label="服务器名称" align="center">
      </el-table-column>
      <el-table-column prop="url" label="服务器地址" align="center">
      </el-table-column>
      <el-table-column prop="username" label="FTP用户名" align="center">
      </el-table-column>
      <el-table-column
        prop="password"
        label="FTP密码"
        align="center"
      ></el-table-column>
      <el-table-column
        align="center"
        label="操作"
        class-name="small-padding"
        width="200"
      >
        <template slot-scope="scope">
          <el-button
            v-permission="'software:update'"
            size="mini"
            type="primary"
            @click="editEquipmentVersion(scope.row)"
            title="修改"
            icon="el-icon-edit"
            circle
          ></el-button>
          <el-button
            v-permission="'software:delete'"
            size="mini"
            type="danger"
            @click="handleDelete(scope.row.rowId)"
            title="删除"
            icon="el-icon-delete"
            circle
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryForm.current"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="queryForm.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="queryForm.total"
      >
      </el-pagination>
    </div>

    <el-dialog
      :title="'新增服务器'"
      :visible.sync="dialogAddFormVisible"
      width="40%"
    >
      <el-form
        :model="addForm"
        label-width="160px"
        :rules="addFormRules"
        ref="addForm"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="服务器名称" prop="name">
              <el-input
                v-model="addForm.name"
                placeholder="请输入服务器名称"
                auto-complete="off"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="服务器URL" prop="url">
              <el-input
                v-model="addForm.url"
                placeholder="请输入服务器URL"
                auto-complete="off"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="FTP用户名" prop="username">
              <el-input
                v-model="addForm.username"
                placeholder="请输入FTP用户名"
                auto-complete="off"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="FTP密码" prop="password">
              <el-input
                v-model="addForm.password"
                placeholder="请输入FTP密码"
                auto-complete="off"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogAddFormVisible = false">取 消</el-button>
        <el-button :loading="confirmLoading" type="primary" @click="execAddForm"
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <el-dialog
      :title="'修改服务器'"
      :visible.sync="dialogEditFormVisible"
      width="40%"
    >
      <el-form
        :model="editForm"
        label-width="160px"
        :rules="editFormRules"
        ref="editForm"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="服务器名称" prop="name">
              <el-input
                v-model="editForm.name"
                placeholder="请输入服务器名称"
                auto-complete="off"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="服务器URL" prop="url">
              <el-input
                v-model="editForm.url"
                placeholder="请输入服务器URL"
                auto-complete="off"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="FTP用户名" prop="username">
              <el-input
                v-model="editForm.username"
                placeholder="请输入FTP用户名"
                auto-complete="off"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="FTP密码" prop="password">
              <el-input
                v-model="editForm.password"
                placeholder="请输入FTP密码"
                auto-complete="off"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogEditFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="execEditForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { editEquipmentVersion, bindDevices } from '@/api/terminal'
import {
  getPackageList,
  uploadFile,
  addPackage,
  deletePackage,
  editPackage
} from '@/api/server'
import { queryProvince, getCity, getDistrict } from '@/api/area'
import {
  selectAllCommunity,
  selectByCommunityIdBuilding,
  selectByBuildingUnit,
  selectAllHouse
} from '@/api/community'
import { findFileTempList } from '@/api/device'
// import calcFileMd5 from '@/utils/ossuploader'

export default {
  name: 'equipment',
  inject: ['reload'],
  data() {
    var checkNum = (rule, value, callback) => {
      if (!/^[0-9]*$/g.test(value)) {
        callback(new Error('只支持数字'))
      } else {
        callback()
      }
    }
    var checkVersion = (rule, value, callback) => {
      if (/^[0-9a-zA-Z.]*$/g.test(value)) {
        callback()
      } else {
        callback(new Error('格式不正确'))
      }
    }
    return {
      confirmLoading: false,
      dialogAddFormVisible: false,
      dialogEditFormVisible: false,
      dialogBindFormVisible: false,
      loading: false,
      queryForm: {
        current: 1,
        pages: 0,
        total: 0,
        size: 10,
        status: undefined,
        title: undefined
      },
      addFormRules: {
        name: [{ required: true, message: '请输入服务器名', trigger: 'blur' }],
        url: [
          { required: true, message: '请输入服务器URL', trigger: 'change' }
        ],
        username: [
          { required: true, message: '请输入FTP用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入FTP密码', trigger: 'blur' }
        ]
      },
      addForm: {
        clientOs: '1'
      },
      editFormRules: {
        name: [{ required: true, message: '请输入服务器名', trigger: 'blur' }],
        url: [
          { required: true, message: '请输入服务器URL', trigger: 'change' }
        ],
        username: [
          { required: true, message: '请输入FTP用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入FTP密码', trigger: 'blur' }
        ]
      },
      editForm: {},
      bindFormRules: {
        deviceType: [
          { required: true, message: '请选择门类型', trigger: 'change' }
        ],
        regionRange: [
          { required: true, message: '请选择区域范围', trigger: 'change' }
        ]
      },
      bindForm: {},
      regionRangeOptions: [],
      doorType: {
        '1': '单元门'
      },
      records: [],
      provinces: [],
      citys: [],
      districts: [],
      communitys: [],
      buildings: [],
      units: [],
      houses: [],
      isRange: false,
      isProvince: false,
      isCity: false,
      isDistrict: false,
      isComm: false,
      isBuild: false,
      isUnit: false,
      isHouse: false,
      fileDate: '',
      filesAdd: [],
      filesEdit: [],
      temps: [],
      msg: ''
    }
  },
  created() {
    // 初始化一次oss client,如果初始化过一次返回上一次初始化对象
    this.initOssClient().then(_ => {
      this.doQuery()
    })
    // this.reload()
    // this.doQuery()
  },
  methods: {
    removeFileEdit(file, fileList) {
      this.filesEdit = []
      this.editForm.versionUrl = null
      this.editForm.fileName = null
      this.editForm.newFileName = null
      this.editForm.originalFilename = null
    },
    removeFileAdd(file, fileList) {
      this.filesAdd = []
      this.addForm.versionUrl = null
      this.addForm.fileName = null
      this.addForm.newFileName = null
      this.addForm.originalFilename = null
    },
    upload(options) {
      const formData = new FormData()
      formData.append('file', options.file)
      uploadFile(formData).then(({ data: { data } }) => {
        this.$message({
          showClose: true,
          message: '上传成功',
          type: 'success'
        })
        if (this.dialogAddFormVisible) {
          this.addForm.versionUrl = data.fileName
          this.addForm.fileName = data.fileName
          this.addForm.newFileName = data.newFileName
          this.addForm.originalFilename = data.originalFilename
        }
        if (this.dialogEditFormVisible) {
          this.editForm.versionUrl = data.fileName
          this.editForm.fileName = data.fileName
          this.editForm.newFileName = data.newFileName
          this.editForm.originalFilename = data.originalFilename
        }

        this.$forceUpdate()
      })
      // this.uploadForElement(options)
    },
    uploadFileAdd(response, file, fileList) {
      debugger
      this.addForm.versionUrl =
        'https://keisdom.oss-cn-hangzhou.aliyuncs.com' + response.name
      this.addForm.md5Code = response.uniqueId
    },
    uploadFileEdit(response, file, fileList) {
      this.editForm.versionUrl =
        'https://keisdom.oss-cn-hangzhou.aliyuncs.com' + response.name
      this.editForm.md5Code = response.uniqueId
    },
    handleCurrentChange(current) {
      this.queryForm.current = current
      this.doQuery()
    },
    handleSizeChange(size) {
      this.queryForm.size = size
      this.doQuery()
    },
    doQuery() {
      this.loading = true
      const queryForm = this.queryForm
      const params = {
        ...this.queryForm
      }
      this.queryForm = params
      params.page = this.queryForm.current
      delete params.current
      getPackageList({
        ...params
      }).then(({ data: { data } }) => {
        this.queryForm.current = data.current
        this.queryForm.pages = data.pages
        this.queryForm.total = data.total
        this.queryForm.size = data.size
        this.records = data.records
        this.loading = false
      })
    },
    handleDelete(rowId) {
      this.$confirm('此操作将删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deletePackage(rowId).then(({ data: { data, msg } }) => {
          this.doQuery()
          this.$message({
            showClose: true,
            message: msg,
            type: 'success'
          })
        })
      })
    },
    openAddDialog() {
      this.filesAdd = []
      findFileTempList().then(({ data: { code, data, msg } }) => {
        this.loading = false
        if (code === 0) {
          this.temps = data
        }
      })
      this.dialogAddFormVisible = true
      this.$refs.addForm && this.$refs.addForm.resetFields()
    },
    optionChange(val) {
      this.temps.forEach(item => {
        if (val === item.rowId) {
          this.msg = item.isOpen
        }
      })
    },
    execAddForm() {
      this.$refs.addForm.validate(valid => {
        if (valid) {
          const params = {
            ...this.addForm
          }
          addPackage({
            ...params
          }).then(({ data: { code, msg, data } }) => {
            if (code === 0) {
              this.doQuery()
              this.dialogAddFormVisible = false
            }
            this.$message({
              showClose: true,
              message: msg,
              type: code === 0 ? 'success' : 'error'
            })
          })
        } else {
          return false
        }
      })
    },
    openEditDialog() {
      this.editForm = {}
      this.dialogEditFormVisible = true
      this.$refs.editForm && this.$refs.editForm.resetFields()
    },
    editEquipmentVersion(row) {
      this.openEditDialog()
      this.editForm = {
        ...row
      }
    },
    execEditForm() {
      this.$refs.editForm.validate(valid => {
        if (valid) {
          const params = {
            name: this.editForm.name,
            rowId: this.editForm.rowId,
            url: this.editForm.url,
            username: this.editForm.username,
            password: this.editForm.password
          }
          editPackage({
            ...params
          }).then(({ data: { code, msg, data } }) => {
            if (code === 0) {
              this.doQuery()
              this.dialogEditFormVisible = false
            }
            this.$message({
              showClose: true,
              message: msg,
              type: code === 0 ? 'success' : 'error'
            })
          })
        } else {
          return false
        }
      })
    },
    bindDevices(row) {
      this.openBindDialog(row)
      this.clearIsShow()
    },
    typeChange() {
      this.isRange = true
      this.regionRangeOptions = []
      if (this.bindForm.deviceType === '0') {
        this.regionRangeOptions = {
          '1': '省',
          '2': '市',
          '3': '区',
          '4': '小区'
        }
      } else if (this.bindForm.deviceType === '1') {
        this.regionRangeOptions = {
          // '1': '省',
          // '2': '市',
          // '3': '区',
          // '4': '小区',
          // '5': '楼栋',
          '6': '单元'
        }
      } else {
        this.regionRangeOptions = {
          '1': '省',
          '2': '市',
          '3': '区',
          '4': '小区',
          '5': '楼栋',
          '6': '单元',
          '7': '室'
        }
      }
    },
    clearIsShow() {
      this.isProvince = false
      this.isCity = false
      this.isDistrict = false
      this.isComm = false
      this.isBuild = false
      this.isUnit = false
      this.isHouse = false
    },
    rangeChange() {
      this.clearIsShow()
      if (this.bindForm.regionRange === '1') {
        this.isProvince = true
      } else if (this.bindForm.regionRange === '2') {
        this.isProvince = true
        this.isCity = true
      } else if (this.bindForm.regionRange === '3') {
        this.isProvince = true
        this.isCity = true
        this.isDistrict = true
      } else if (this.bindForm.regionRange === '4') {
        this.isProvince = true
        this.isCity = true
        this.isDistrict = true
        this.isComm = true
      } else if (this.bindForm.regionRange === '5') {
        this.isProvince = true
        this.isCity = true
        this.isDistrict = true
        this.isComm = true
        this.isBuild = true
      } else if (this.bindForm.regionRange === '6') {
        this.isProvince = true
        this.isCity = true
        this.isDistrict = true
        this.isComm = true
        this.isBuild = true
        this.isUnit = true
      } else if (this.bindForm.regionRange === '7') {
        this.isProvince = true
        this.isCity = true
        this.isDistrict = true
        this.isComm = true
        this.isBuild = true
        this.isUnit = true
        this.isHouse = true
      }
    },
    provChange() {
      getCity(this.bindForm.provinceId).then(({ data: { data } }) => {
        this.citys = []
        this.districts = []
        this.communitys = []
        this.buildings = []
        this.units = []
        this.houses = []
        this.citys = data
        this.bindForm = {
          rowId: this.bindForm.rowId,
          deviceType: this.bindForm.deviceType,
          regionRange: this.bindForm.regionRange,
          provinceId: this.bindForm.provinceId,
          cityId: '',
          districtId: '',
          communityId: '',
          buildingId: '',
          unitId: '',
          houseId: ''
        }
      })
    },
    cityChange() {
      getDistrict(this.bindForm.cityId).then(({ data: { data } }) => {
        this.districts = []
        this.communitys = []
        this.buildings = []
        this.units = []
        this.houses = []
        this.districts = data
        this.bindForm = {
          rowId: this.bindForm.rowId,
          deviceType: this.bindForm.deviceType,
          regionRange: this.bindForm.regionRange,
          provinceId: this.bindForm.provinceId,
          cityId: this.bindForm.cityId,
          districtId: '',
          communityId: '',
          buildingId: '',
          unitId: '',
          houseId: ''
        }
      })
    },
    distChange() {
      selectAllCommunity(this.bindForm.districtId).then(
        ({ data: { data } }) => {
          this.communitys = []
          this.buildings = []
          this.units = []
          this.houses = []
          this.communitys = data
          this.bindForm = {
            rowId: this.bindForm.rowId,
            deviceType: this.bindForm.deviceType,
            regionRange: this.bindForm.regionRange,
            provinceId: this.bindForm.provinceId,
            cityId: this.bindForm.cityId,
            districtId: this.bindForm.districtId,
            communityId: '',
            buildingId: '',
            unitId: '',
            houseId: ''
          }
        }
      )
    },
    commChange() {
      selectByCommunityIdBuilding(this.bindForm.communityId).then(
        ({ data: { data } }) => {
          this.buildings = []
          this.units = []
          this.houses = []
          this.buildings = data
          this.bindForm = {
            rowId: this.bindForm.rowId,
            deviceType: this.bindForm.deviceType,
            regionRange: this.bindForm.regionRange,
            provinceId: this.bindForm.provinceId,
            cityId: this.bindForm.cityId,
            districtId: this.bindForm.districtId,
            communityId: this.bindForm.communityId,
            buildingId: '',
            unitId: '',
            houseId: ''
          }
        }
      )
    },
    buildChange() {
      selectByBuildingUnit(this.bindForm.buildingId).then(
        ({ data: { data } }) => {
          this.units = []
          this.houses = []
          this.units = data
          this.bindForm = {
            rowId: this.bindForm.rowId,
            deviceType: this.bindForm.deviceType,
            regionRange: this.bindForm.regionRange,
            provinceId: this.bindForm.provinceId,
            cityId: this.bindForm.cityId,
            districtId: this.bindForm.districtId,
            communityId: this.bindForm.communityId,
            buildingId: this.bindForm.buildingId,
            unitId: '',
            houseId: ''
          }
        }
      )
    },
    unitChange() {
      selectAllHouse(this.bindForm.unitId).then(({ data: { data } }) => {
        this.houses = []
        this.houses = data
        this.bindForm = {
          rowId: this.bindForm.rowId,
          deviceType: this.bindForm.deviceType,
          regionRange: this.bindForm.regionRange,
          provinceId: this.bindForm.provinceId,
          cityId: this.bindForm.cityId,
          districtId: this.bindForm.districtId,
          communityId: this.bindForm.communityId,
          buildingId: this.bindForm.buildingId,
          unitId: this.bindForm.unitId,
          houseId: ''
        }
      })
    },
    execBindForm() {
      this.$refs.bindForm.validate(valid => {
        if (valid) {
          if (this.bindForm.provinceId === undefined) {
            this.$message({
              showClose: true,
              message: '请选择区域范围',
              type: 'warning'
            })
          } else {
            if (this.bindForm.regionRange === '1') {
              this.bindForm.regionId = this.bindForm.provinceId
            } else if (this.bindForm.regionRange === '2') {
              this.bindForm.regionId = this.bindForm.cityId
            } else if (this.bindForm.regionRange === '3') {
              this.bindForm.regionId = this.bindForm.districtId
            } else if (this.bindForm.regionRange === '4') {
              this.bindForm.regionId = this.bindForm.communityId
            } else if (this.bindForm.regionRange === '5') {
              this.bindForm.regionId = this.bindForm.buildingId
            } else if (this.bindForm.regionRange === '6') {
              this.bindForm.regionId = this.bindForm.unitId
            } else if (this.bindForm.regionRange === '7') {
              this.bindForm.regionId = this.bindForm.houseId
            }
            bindDevices(this.bindForm).then(({ data: { code, msg, data } }) => {
              if (code === 0) {
                this.doQuery()
                this.dialogBindFormVisible = false
              }
              this.$message({
                showClose: true,
                message: msg,
                type: code === 0 ? 'success' : 'error'
              })
            })
          }
        } else {
          return false
        }
      })
    }
  },
  components: {}
}
</script>

<style scoped></style>
